package asunit.framework {
	import flash.net.NetConnection;
	import flash.net.URLRequest;
	import flash.net.URLLoader;
	import flash.events.*;
	import flash.errors.IllegalOperationError;

	/**
	 * Extend this class if you have a TestCase that requires the
	 * asynchronous load of external data.
	 */
	public class AsynchronousTestCase extends TestCase {
		
		public function AsynchronousTestCase(testMethod:String = null) {
			super(testMethod);
		}

		protected function configureListeners(loader:URLLoader):void {
			loader.addEventListener(Event.COMPLETE, completeHandler);
			loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
			loader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			loader.addEventListener(Event.OPEN, openHandler);
			loader.addEventListener(ProgressEvent.PROGRESS, progressHandler);
			loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
		}
		
		protected function configureNetConnectionListeners(connection:NetConnection):void
		{
			connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
			connection.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
			connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
			connection.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
		}
		
		protected function asyncErrorHandler(e:AsyncErrorEvent):void 
		{
			this.getResult().addError(this, e.error);
			this.isComplete = true;
		}
		
		protected function netStatusHandler(e:NetStatusEvent):void 
		{
			
		}
		/**
		 * [abstract] Override this method in a subclass to listen for Event.COMPLETE events.
		 * You must call the corresponding configure*() method on your EventDispatcher instance for this
		 * to fire.
		 * @param	event	The Event object.
		 */
		protected function completeHandler(event:Event):void {}
		/**
		 * [abstract] Override this method in a subclass to listen for HTTPStatusEvent events.
		 * You must call the corresponding configure*() method on your EventDispatcher instance for this
		 * to fire.
		 * @param	event	The Event object.
		 */
		protected function httpStatusHandler(event:HTTPStatusEvent):void {}
		
		protected function ioErrorHandler(event:IOErrorEvent):void {
			result.addError(this, new IllegalOperationError(event.toString()));
			isComplete = true;
		}

		protected function openHandler(event:Event):void {}

		protected function progressHandler(event:ProgressEvent):void {}

		protected function securityErrorHandler(event:SecurityErrorEvent):void {
			result.addError(this, new IllegalOperationError(event.toString()));
			isComplete = true;
		}
	}
}